package com.duoduo.demo.rabbitmq.rpc;

import java.io.UnsupportedEncodingException;

import javax.annotation.Resource;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class RabbitmqRpcServer {

	@Resource(name = "replyRabbitTemplate")
	private AmqpTemplate rabbitTemplate;

	// @RabbitHandler
	// public void process(String message) {
	// System.out.println("[SERVER]Receiver Text: " + message);
	// }

	@RabbitListener(queues = "${rmq.rpc.requestqueue}")
	public void process(Message message) {
		System.out.println("[SERVER]Receiver RPC: " + message.toString());
		if (message == null || message.getBody() == null || message.getMessageProperties() == null) {
			System.out.println("[SERVER]	Message is invalid");
			return;
		}

		// String correlationId = message.getMessageProperties().getCorrelationIdString();
		// if (StringUtils.isEmpty(correlationId) && StringUtils.hasText(message.getMessageProperties().getMessageId()))
		// {
		// correlationId = message.getMessageProperties().getMessageId();
		// message.getMessageProperties().setCorrelationIdString(correlationId);
		// }
		// System.out.println("[SERVER] RPC correlationId: " + correlationId);

		String replyTo = message.getMessageProperties().getReplyTo();
		System.out.println("[SERVER]	RPC replyTo: " + replyTo);

		String data = "";
		try {
			data = "result: " + new String(message.getBody(), "UTF-8");
			System.out.println("[SERVER]	RPC data: " + data);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		Message response = new Message(data.getBytes(), message.getMessageProperties());
		rabbitTemplate.send(replyTo, response);
	}

	public void reply() {
		System.out.println("[SERVER]System time: " + System.currentTimeMillis());
	}
}
